package com.dxy.auth.controller;

import com.dxy.auth.service.AuthService;
import com.dxy.common.dto.UserDTO;
import com.dxy.common.utils.JwtUtil;
import com.dxy.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result applyToken(UserDTO userDTO) {
        log.info("[用户登录]:{}", userDTO);
        if (StringUtils.isBlank(userDTO.getUsername())) {
            return Result.fail("用户名不能为空！");
        }
        if (StringUtils.isBlank(userDTO.getPassword())) {
            return Result.fail("密码不能为空！");
        }
        String token = authService.login(userDTO.getUsername(), userDTO.getPassword());
        return Result.ok(token);
    }

    /**
     * 刷新token
     */
    @GetMapping("/refreshToken")
    public Result refreshToken(HttpServletRequest request) {
        log.info("[刷新token]");
        String token = request.getHeader(JwtUtil.TOKEN_NAME);
        if (StringUtils.isBlank(token)) {
            return Result.fail("token不能为空！");
        }
        String newToken = JwtUtil.refreshToken(token);
        return Result.ok(newToken);
    }

    /**
     * 检查权限
     */
    @PostMapping("/checkPermission")
    public Result checkPermission(HttpServletRequest request, String url) {
        log.info("[检查权限]");
        String token = request.getHeader(JwtUtil.TOKEN_NAME);
        Integer userId = Integer.parseInt(JwtUtil.getUniqueId(token));
        boolean res = authService.checkPermission(userId, url);
        return Result.ok(res);
    }


}
